import axios from 'axios';

const API_URL = 'http://localhost:8080/api/users'; // 后端API基础URL，请根据实际情况修改

// 获取存储在localStorage中的token
const getToken = () => {
    // 优先从单独存储的token获取
    const token = localStorage.getItem('token');
    if (token) {
        return token;
    }
    
    // 如果没有单独存储，从用户对象中获取
    try {
        const user = JSON.parse(localStorage.getItem('user'));
        if (user && user.token) {
            return user.token;
        }
    } catch (error) {
        console.error('Error parsing user from localStorage:', error);
    }
    return null;
};

// 创建带有认证头的axios实例
const axiosInstance = axios.create();

axiosInstance.interceptors.request.use(
    (config) => {
        const token = getToken();
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
            console.log('Adding auth token to request:', `Bearer ${token.substring(0, 15)}...`); // Log token partially for debugging
        } else {
            console.warn('No authentication token found');
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

/**
 * 获取当前登录用户的个人信息
 */
const getCurrentUserProfile = () => {
    return axiosInstance.get(`${API_URL}/profile`);
};

/**
 * 更新当前登录用户的个人信息
 * @param {object} userData - 包含要更新的用户信息的对象, 例如 { email, phone }
 */
const updateCurrentUserProfile = (userData) => {
    return axiosInstance.put(`${API_URL}/profile`, userData);
};

const userService = {
    getCurrentUserProfile,
    updateCurrentUserProfile,
};

export default userService; 